import json
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import datetime
import os
import shutil
import zipfile



class SendMail:
    def __init__(self):

        # 邮件配置
        self.smtp_host = 'smtp.qq.com'
        self.smtp_port = 465
        self.sender_email = '3296232192@qq.com'
        self.sender_password = 'shahzwlnwzmudahb'
        self.recipient_email = ['16607054615@163.com']
        self.subject = 'call项目日志提醒'
        self.message = f''

        # 创建带附件的邮件对象
        self.message_obj = MIMEMultipart()
        self.message_obj['From'] = self.sender_email
        self.message_obj['To'] = self.recipient_email[0]
        # 添加抄送
        cc_str = ', '.join(self.recipient_email[1:])
        self.message_obj['Cc'] = cc_str
        self.message_obj['Subject'] = self.subject

        # 添加正文

    def set_mail_content(self, message):
        self.message_obj.attach(MIMEText(message))

    def set_proxy(self):
        proxy_host = '10.30.7.36'
        proxy_port = 3300  # Replace with your actual proxy port
        socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, proxy_host, proxy_port)
        socks.wrapmodule(smtplib)

    def add_attach(self, file):
        # 添加超大附件
        file_path = "path_to_your_large_file"  # 替换为你的超大附件文件路径
        attachment = open(file_path, "rb")
        attach_part = MIMEBase("application", "octet-stream")
        attach_part.set_payload(attachment.read())
        encoders.encode_base64(attach_part)
        attach_part.add_header(
            "Content-Disposition",
            f"attachment; filename= {file_path}",
        )
        self.message_obj.attach(attach_part)

        # # 添加附件
        # filename = file  # 附件文件名
        # with open(filename, 'rb') as f:
        #     attachment = MIMEApplication(f.read(), Name=filename)
        #     attachment['Content-Disposition'] = f'attachment; filename="{filename}"'
        #     self.message_obj.attach(attachment)

    def send_mail(self):
        # 连接到SMTP服务器并发送邮件
        try:
            with smtplib.SMTP_SSL(self.smtp_host, self.smtp_port) as server:
                server.login(self.sender_email, self.sender_password)
                server.send_message(self.message_obj)
            print('邮件发送成功')
        except Exception as e:
            print('邮件发送失败:', str(e))

    def get_previous_filename(self):
        # 获取当前日期
        current_date = datetime.date.today()

        # 获取前一天的日期
        previous_date = current_date - datetime.timedelta(days=1)

        # 格式化日期为字符串（例如：20231231）
        previous_date_str = previous_date.strftime('%Y%m%d')
        return previous_date_str

    def compress_files(self, path):
        filename = self.get_previous_filename()
        # 要压缩的目录和文件列表
        source_paths = [
            # (f"{path}/{filename}", ''),
            (f'{path}/{filename}.csv', '')
        ]

        # 压缩文件名为example.zip
        zip_filename = f'{path.split("/")[-1]}_{filename}.zip'

        # 使用with上下文管理器创建ZipFile对象并打开压缩文件
        with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zip_file:

            # 逐个添加每个目录和文件
            for path, prefix in source_paths:

                # 如果是目录
                if os.path.isdir(path):
                    # 递归遍历并把整个目录加入到zip文件中
                    for root, dirs, files in os.walk(path):
                        for file in files:
                            file_path = os.path.join(root, file)
                            zip_file.write(file_path, os.path.join(prefix, file))

                # 如果是文件
                else:
                    zip_file.write(path, os.path.join(prefix, os.path.basename(path)))


if __name__ == '__main__':
    mail = SendMail()
    mail.set_mail_content('test')

    # tool.add_attach(f'Sftp.py')
    mail.send_mail()
